

import 'package:bike_ride/api/common_repository.dart';
import 'package:bike_ride/common/util/account_manager.dart';
import 'package:bike_ride/common/util/hysize_fit.dart';
import 'package:bike_ride/common/util/map_navigator.dart';
import 'package:bike_ride/common/widget/dialog/mydialog.dart';
import 'package:bike_ride/common/widget/xb_button.dart';
import 'package:bike_ride/model/cyling/view_model/cyling_vm.dart';
import 'package:bike_ride/generated/l10n.dart';
import 'package:bike_ride/res/style/color_styles.dart';
import 'package:bike_ride/res/style/text_styles.dart';
import 'package:bike_ride/router/navigator_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

/// 还车失败弹窗
class IrregularStopMode extends StatefulWidget {
  final CyclingViewModel viewModel;

  const IrregularStopMode({super.key, required this.viewModel});

  @override
  State<IrregularStopMode> createState() => _IrregularStopModeState();
}

class _IrregularStopModeState extends State<IrregularStopMode> {
  late Map<int, Map<String, dynamic>> stopAreaOptions;
  late CyclingViewModel viewModel;
  late int type;

  @override
  void initState() {
    super.initState();
    viewModel = widget.viewModel;
    type = 0;
    switch(viewModel.returnBikeM?.statusCode){
      case 51036://检测到不在停车区
      case 51070:// 新版不在停车区
        type = 2;
        break;
      case 51037:// 检测到禁停区
      case 51084:// 新版检测到禁停区
        type = 3;
        break;
      case 51039:// 检测到不在运营区内
      case 51087:// 新版检测到不在运营区
        type = 4;
        break;
    }
    stopAreaOptions = {
      0: {
        'label': S.current.parkP,
        'labelTip': S.current.parkPTips,
        'mapTip': S.current.standardPark,
        'btnText': S.current.comfireReturn,
        'mapUrl': 'assets/common_v2/map_stop_1.png',
      },
      2: {
        'label': S.current.outsideParkAreaLabel,
        'labelTip': S.current.outsideParkAreaLabelTip,
        'wraningTip': S.current.outsideParkAreaWraningTip,
        'mapTip': S.current.unStandardPark,
        'btnText': S.current.stillReturn,
        'mapUrl': 'assets/common_v2/map_stop_2.png',
      },
      3: {
        'label': S.current.insideNoparkAreaLabel,
        'labelTip': S.current.insideNoparkAreaLabelTip,
        'wraningTip': S.current.insideNoparkAreaWraningTip,
        'mapTip': S.current.unStandardPark,
        'btnText': S.current.stillReturn,
        'mapUrl': 'assets/common_v2/map_stop_3.png',
      },
      4: {
        'label': S.current.outsideOperationLabel,
        'labelTip': S.current.outsideOperationLabelTip,
        'wraningTip': S.current.outsideOperationWraningTip,
        'mapTip': S.current.unStandardPark,
        'btnText': S.current.stillReturn,
        'mapUrl': 'assets/common_v2/map_stop_4.png',
      },
    };

    updateStopAreaOptions();
  }

  void updateStopAreaOptions() {
    if (viewModel.bikeInfoM?.feeInfo != null) {
      final serviceOutwardFee = viewModel.bikeInfoM!.feeInfo!.serviceOutwardFee;
      final trafficFare = viewModel.bikeInfoM!.feeInfo!.trafficFare;
      final nostopOutwardFee = viewModel.bikeInfoM!.feeInfo!.nostopOutwardFee;

      setState(() {
        stopAreaOptions[2]!['labelTip'] = '${S.current.noParkP} $trafficFare${S.current.yuan} ${S.current.serviceFee}';
        stopAreaOptions[2]!['wraningTip'] = '${S.current.noParkPTips} $trafficFare${S.current.yuan} ${S.current.serviceFee}';
        stopAreaOptions[3]!['labelTip'] = '${S.current.inForbiddenP} $nostopOutwardFee${S.current.yuan} ${S.current.serviceFee}';
        stopAreaOptions[3]!['wraningTip'] = '${S.current.inForbiddenPTips} $nostopOutwardFee${S.current.yuan} ${S.current.serviceFee}';
        stopAreaOptions[4]!['labelTip'] = '${S.current.outOperationP} $serviceOutwardFee${S.current.yuan} ${S.current.serviceFee}';
        stopAreaOptions[4]!['wraningTip'] = '${S.current.outOperationPTips} $serviceOutwardFee${S.current.yuan} ${S.current.serviceFee}';
      });
    }
  }

  ///前往最近停车区
  Future onShowParkingArea() async {
    EasyLoading.show(dismissOnTap: true);
    await viewModel.getBikeRealTime(viewModel.vid!);
    if(viewModel.bikeRealTimeM != null){
      final result = await CommonRepository.getNearbyParkIdl(lat: viewModel.bikeRealTimeM!.lat!, lng: viewModel.bikeRealTimeM!.lng!,type: 1,isShowEmptyTip:true);
      if(result.isNotEmpty && mounted){
        EasyLoading.dismiss();
        MapNavigatorUtil.showMapModalPopup(
            context, result.first.lng, result.first.lat);
      }
    }

  }

  ///仍要还车
  Future handleReturnPre()async{
    if(type == 0){
      viewModel.returnBike(viewModel.vid!, viewModel.orderId!,skipParkingCheck: true);
    }else{
      showAlertDialog(
        context: context,
        title: stopAreaOptions[type]!['label'] ,
        content: Text(stopAreaOptions[type]!['wraningTip'],style: TextStyles.style_small_tips,),
        confirmName: S.current.stillReturn,
        onConfirm: () {
          NavigatorUtil.back(context,count: 2);
          viewModel.returnBike(viewModel.vid!, viewModel.orderId!,skipParkingCheck: true);
        },
        onCancel: () {
          Navigator.of(context).pop();
        },
      );
    }
  }

  bool get checkReturnBtn {
    // 开启强制规范还车，站点外、运营区外，隐藏仍要还车按钮
    if (AccountManager.areaInfoM?.isRfidReturnCheck == 1) {
      if ([2, 4].contains(type)) {
        return false;
      }
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16.0),
      decoration: BoxDecoration(
        color: ColorStyles.color_FFFFFF,
        borderRadius: BorderRadius.only(topLeft: Radius.circular(40.rpx),topRight: Radius.circular(40.rpx))
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(Icons.error_rounded,color: ColorStyles.color_FF5500,),
              Text(
                stopAreaOptions[type]?['label'] ?? '',
                style: TextStyle(fontSize: 32.rpx,color: ColorStyles.color_FF5500),
              ),
            ],
          ),
          SizedBox(height: 16.rpx),
          Text(
            stopAreaOptions[type]?['labelTip'] ?? '',
            style: TextStyle(color: type == 0 ? Colors.grey : ColorStyles.color_FF5500),
          ),
          const SizedBox(height: 4.0),
          Row(
            children: [
              Icon(
                Icons.notifications,
                color: type == 0 ? Colors.green : Colors.red,
                size: 20.0,
              ),
              const SizedBox(width: 8.0),
              Text(stopAreaOptions[type]?['mapTip'] ?? ''),
            ],
          ),
          const SizedBox(height: 16.0),
          Image.asset(stopAreaOptions[type]?['mapUrl']!),
          const SizedBox(height: 16.0),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              if (type == 0)
                Expanded(child: XbButton(
                  onPressed: handleReturnPre,
                  color: ColorStyles.color_1082FF,
                  child: Text(stopAreaOptions[type]?['btnText'] ?? ''),
                )),
              if (type != 0)
                Expanded(
                  child: Row(
                    children: [
                      Expanded(
                        child: ValueListenableBuilder(valueListenable: widget.viewModel.isCheckParking,builder: (context,isChecking,_){
                          return XbButton(
                            onPressed: ()async{
                              final result = await viewModel.checkParking(viewModel.vid!);
                              if(result && mounted){
                                Navigator.pop(context,true);
                                viewModel.returnBike(viewModel.vid!, viewModel.orderId!);
                              }
                            },
                            isDefault: false,
                            color: ColorStyles.color_EEEEEE,
                            child: Text(isChecking ? '${S.current.verifyLocation}...' : S.current.reVerifyLocation,style: const TextStyle(color: ColorStyles.color_1082FF),),
                          );
                        },),
                      ),
                      SizedBox(width: 28.rpx,),
                      if (checkReturnBtn)
                        Expanded(
                          child: XbButton(
                            onPressed: handleReturnPre,
                            isDefault: false,
                            color: ColorStyles.color_FF5500,
                            child: Text(stopAreaOptions[type]?['btnText'] ?? ''),
                          ),
                        ),
                      if (!checkReturnBtn)
                        Expanded(
                          child: XbButton(
                            onPressed: onShowParkingArea,
                            isDefault: false,
                            color: ColorStyles.color_FF5500,
                            child: Text(S.current.nearestParkArea),
                          ),
                        ),
                    ],
                  ),
                ),
            ],
          ),
          if (type != 0 && checkReturnBtn)
            ...[
              SizedBox(height: 16.rpx,),
              Row(
                children: [
                  Expanded(child: XbButton(
                    onPressed: onShowParkingArea,
                    isDefault: false,
                    color: ColorStyles.color_1082FF,
                    child: Text(S.current.nearestParkArea),
                  ),)
                ],
              )
            ]
        ],
      ),
    );
  }
}